package com.aishare.b2c.interceptor;

import com.aishare.b2c.entity.user.User;
import com.aishare.b2c.service.user.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import util.JasonUtil;
import util.JsonResponse;
import util.SessionUtil;
import util.SpringContextUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class QqWebInterceptor implements HandlerInterceptor {


    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {

    }

    /**
     * true表示继续流程（如调用下一个拦截器或处理器）；
     * false表示流程中断（如登录检查失败），不会继续调用其他的拦截器或处理器，此时我们需要通过response来产生响应；
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = SessionUtil.getUser(request);
        if (user != null) {
            //session 中有用户信息

            return true;
        }else
        {
            //使用手机号登陆
            String  phone = String.valueOf(request.getParameter("tokenPhone"));
            if (!StringUtils.isBlank(phone) && !"null".equals(phone)) {

               IUserService userService = (IUserService)SpringContextUtil.getBean("userServiceImpl");
                user = userService.getOneByPhone(phone);
                if(user != null)
                {
                    SessionUtil.setUser(request,user);
                }
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setRes(301);
        response.getWriter().write(JasonUtil.toJson(jsonResponse));
        //response.getWriter().write("{\"res\":301}");

        return false;
    }
}
